package com.zhuxulin.midi.examples;

import java.io.File;
import java.io.IOException;

import com.zhuxulin.midi.MidiFile;
import com.zhuxulin.midi.event.ChannelEvent;
import com.zhuxulin.midi.event.MidiEvent;
import com.zhuxulin.midi.event.NoteOn;
import com.zhuxulin.midi.event.meta.Tempo;
import com.zhuxulin.midi.util.MidiEventListener;
import com.zhuxulin.midi.util.MidiProcessor;

public class EventPrinter implements MidiEventListener {

	private String mLabel;
	public EventPrinter(String label) {
		mLabel = label;
	}

	// 0. Implement the listener functions that will be called by the MidiProcessor
	@Override
	public void onStart(boolean fromBeginning) {
		
		if(fromBeginning) {
			System.out.println(mLabel + " Started!");
		}
		else {
			System.out.println(mLabel + " resumed");
		}
	}

	@Override
	public void onEvent(MidiEvent event, long ms) {
		System.out.println(mLabel + " received event: " + event);
//		System.out.println(event.getCmd());
		if(event instanceof ChannelEvent){
			System.out.println("ChannelEvent!");
		}
		if (event != null) {
			byte[] cmd = event.getCmd();
			if (cmd != null) {
				for (byte b : cmd) {
					System.out.print(Integer.toHexString(b&0xFF));
					System.out.print("\t");
				}
				System.out.println();
			}
		}
//		byte[] bs=event.getmDelta().getBytes();
//		for (byte b : bs) {
//			System.out.print(b);
//			System.out.print("\t");
//		}
//		System.out.println();
//		event.getDelta();
//		event.getSize();
//		event.getTick();
	}

	@Override
	public void onStop(boolean finished) {
		
		if(finished) {
			System.out.println(mLabel + " Finished!");
		}
		else {
			System.out.println(mLabel + " paused");
		}
	}
	
	public static void main(String[] args) {
		
		// 1. Read in a MidiFile
		MidiFile midi = null;
		try {
			midi = new MidiFile(new File("E:/files/test.mid"));
		} catch(IOException e) {
			System.err.println(e);
			return;
		}
		
		// 2. Create a MidiProcessor
		MidiProcessor processor = new MidiProcessor(midi);
		
		// 3. Register listeners for the events you're interested in
//		EventPrinter ep = new EventPrinter("Individual Listener");
//		processor.registerEventListener(ep, Tempo.class);
//		processor.registerEventListener(ep, NoteOn.class);
		
		// or listen for all events:
//		EventPrinter ep2 = new EventPrinter("Listener For All");
//		processor.registerEventListener(ep2, MidiEvent.class);
		// ChannelEvent
		EventPrinter ep3 = new EventPrinter("Listener For All");
		processor.registerEventListener(ep3, MidiEvent.class);
		
		// 4. Start the processor
		processor.start();
		
		// Listeners will be triggered in real time with the MIDI events
		// And you can pause/resume with stop() and start()
		
//		try {
//			Thread.sleep(10 * 1000);
//			processor.stop();
//
//			Thread.sleep(10 * 1000);
//			processor.start();
//		} catch(Exception e) {}
		
	}
}
